package com.wk.unreal.dingroomserver.interceptor;

import com.wk.unreal.dingroomserver.util.JwtUtil;
import com.wk.unreal.dingroomserver.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 验证请求时是否携带了 token
        String tokenKey = request.getHeader("Authorization");

        try {
            // 通过 tokenKey 去 Redis 里面查询
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            String tokenValue = valueOperations.get(tokenKey);

            // 判断 token 是否过期
            if (tokenValue == null) {
                throw  new RuntimeException();
            }
            // 解析 token , 把解析的相关数据保存到 ThreadLocal 里面(用于后期的操作：修改用户名)
            Map<String, Object> claims = JwtUtil.parseToken(tokenValue);
            ThreadLocalUtil.set(claims);
            // 放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            // 不允许同行
            return  false;
        }
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 销毁数据
        ThreadLocalUtil.remove();
    }
}
